package com.chenyun.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.chenyun.common.constants.AuthConstant;
import com.chenyun.common.context.SpringContext;
import com.chenyun.common.exceptions.BusinessException;
import com.chenyun.system.param.SendSmsParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * CommonServiceImpl：
 * Description:
 *
 * @author: Lonni
 * @date: 2025/3/18 16:54
 */

@Slf4j
@Service
public class CommonServiceImpl implements Serializable {


    @Autowired
    private RedisTemplate redisTemplate;


    public Boolean sengPhoneCode(List<SendSmsParam> params) {
        if (CollectionUtil.isEmpty(params)) {
            throw new BusinessException("参数列表为空!");
        }

        for (SendSmsParam param : params) {
            if (StringUtils.isEmpty(param.getPhone())) {
                throw new BusinessException("手机号不能为空!");
            }
            if (Objects.isNull(param.getType())) {
                throw new BusinessException("业务类型不能为空!");
            }
            String cacheKey = getCacheKey(param);
            if (SpringContext.isTest()) {
                //测试环境 发送6个1
                redisTemplate.opsForValue().set(cacheKey, 111111, 2, TimeUnit.MINUTES);

            } else {
                //TODO 发送逻辑
            }

        }

        return true;
    }


    public Object getPhoneCode(SendSmsParam param) {
        String cacheKey = this.getCacheKey(param);
        return redisTemplate.opsForValue().get(cacheKey);
    }


    public String getCacheKey(SendSmsParam param) {
        String key = AuthConstant.AUTH_SMS_CACHE_KEY;
        key = key.replace("{type}", param.getType().toString())
                .replace("{phone}", param.getPhone());
//        return com.chenyun.common.utils.StringUtils.format(AuthConstant.AUTH_SMS_CACHE_KEY, param.getType(), param.getPhone());
        return key;
    }


}



